/* eslint-disable prettier/prettier */
import React, { Ref, useEffect, useRef, useState } from 'react';
import { Alert, Image, ImageBackground, Modal, StatusBar, Text, TouchableHighlight,ToastAndroid, View ,Animated,Dimensions} from 'react-native';
import styles from './styles';
import { NewWord,GetChaizi } from '../../services/getJsonData';
import {buttons,getbuttons} from '../../services/Randomlist';
import { TouchableOpacity } from 'react-native';
import Sound from 'react-native-sound';
import SoundPlay from '../learn/soundplay';
import getUniqueFileUris from '../learn/getFileList';
import GetjsonData, { Getjsonwords } from '../../services/getJsonData';
import ResultDialog from '../practise/ResultDialog';

const falseSound = new Sound('d.mp3', Sound.MAIN_BUNDLE, (error) => {
  if (error) {
    console.log('failed to load the sound', error);
    return;
  }
  console.log('duration in seconds: ' + falseSound.getDuration() + ' number of channels: ' + falseSound.getNumberOfChannels());
});

const correctSound = new Sound('v.mp3', Sound.MAIN_BUNDLE, (error) => {
  if (error) {
    console.log('failed to load the sound', error);
    return;
  }
  console.log('duration in seconds: ' + correctSound.getDuration() + ' number of channels: ' + correctSound.getNumberOfChannels());
});

const Practise = ({route, navigation}) =>{
  const [huozhong, setHuozhong] = useState<String[]>([]);
  const [characterlist, setCharacterlist] = useState<NewWord[]>([]);
  const [bushou, setBushou] = useState<string[]>([]);
  const [pressbutton, setPressbutton] = useState<buttons[6]>([]);
  const [daan, setDaan] = useState<number>(1);
  const [num, setNum] = useState<number>(0);
  const [word, setWord] = useState<string>('dsfs');
  const [succ, setSucc] = useState<number>(4);
  const [fileUris, setFileUris] = useState<{ [key: string]: string }>({});
  const [unit,setUnit] = useState<String>('unit0');
  const [modalVisible, setModalVisible] = useState(false);
  const [success,setSuccess] = useState<boolean>(true);
  const [backgroundTransparent, setBackgroundTransparent] = useState('transparent');
  const [bgc,setBgc] = useState<String>('unit0');
  const [animationValue] = useState<Array<Animated.Value>>(
    Array.from({ length: 6 }, () => new Animated.Value(0))
  );
  const [animationValue2] = useState<Array<Animated.Value>>(
    Array.from({ length: 6 }, () => new Animated.Value(0))
  );
  const buttonRefs = useRef<(React.RefObject<TouchableOpacity>)[]>(Array.from({ length: 6 }, () => React.createRef<TouchableOpacity>()));
  const [op,setOpcity] = useState<Number>(1);
  const [opt,setOpcityt] = useState<Number>(1);
  const screenCenterX = Dimensions.get('window').width;
  const screenCenterY = Dimensions.get('window').height;
  const animate = (index: number): Promise<void> => {
    setOpcity(0.5);
    return new Promise((resolve) => {
      Animated.timing(animationValue[index], {
        toValue: 20, // 向前移动20个单位
        duration: 100,
        useNativeDriver: true,
        isInteraction: false,
      }).start(() => {
        // 动画完成后反向动画
        Animated.timing(animationValue[index], {
          toValue: -20, // 向后移动20个单位
          duration: 100,
          useNativeDriver: true,
          isInteraction: false,
        }).start(() => {
          // 再次向前移动20个单位
          Animated.timing(animationValue[index], {
            toValue: 20, // 向前移动20个单位
            duration: 100,
            useNativeDriver: true,
            isInteraction: false,
          }).start(() => {
            // 最后回到初始值
            Animated.timing(animationValue[index], {
              toValue: 0, // 回到初始值
              duration: 100,
              useNativeDriver: true,
              isInteraction: false,
            }).start(() => {
              resolve(); // 动画完成，调用 resolve
            });
          });
        });
      });
    });
  };

  const toCenter = (pressbutton: buttons[], buttonRefs: React.RefObject<TouchableOpacity>[]): Promise<void> => {
    return new Promise((resolve) => {
      console.log('toCenter!');
      // 创建一个数组来存放所有的测量Promise
      const measurePromises = pressbutton.map((pressbuttons, index) => {
        return new Promise((measureResolve) => {
          if (bushou.includes(pressbuttons.title) && buttonRefs.current[index].current) {
            // 获取按钮的位置信息
            console.log('判断index----');
            buttonRefs.current[index].current.measure((x, y, width, height, pageX, pageY) => {
              console.log(`Component absolute position: (${pageX}, ${pageY})`);
              console.log(`Component size: ${width} x ${height}`);
              let translationX = screenCenterX / 2 - pageX - width / 2;
              let translationY = screenCenterY / 2 - pageY - height / 2;
              const animation1 = Animated.timing(animationValue[index], {
                toValue: translationX,
                duration: 2000,
                useNativeDriver: true,
              });
              const animation2 = Animated.timing(animationValue2[index], {
                toValue: translationY,
                duration: 2000,
                useNativeDriver: true,
              });
              Animated.parallel([animation1, animation2,]).start(() => {
                setOpcityt(0);
                 
                Animated.sequence([Animated.delay(2000),
                  ...animationValue.map((value, idx) => Animated.timing(value, { toValue: 0, duration: 0, useNativeDriver: true })),
                  ...animationValue2.map((value, idx) => Animated.timing(value, { toValue: 0, duration: 0, useNativeDriver: true })),
                ]).start(() => {setOpcityt(1);resolve();});
              });
            });
          } else {
            console.log(`Button ${index} does not meet conditions or reference is not set.`);
            measureResolve();
          }
        });
      });
  
      // 等待所有的测量Promise完成
      Promise.all(measurePromises).then(() => {
        // 所有按钮都测量完成，可以开始动画
      });
    });
  };
  // 直接使用Animated.Value，不需要访问_value属性

  const showResultDialog = () => {
    setModalVisible(true);
    setSuccess(true);
    setBackgroundTransparent('rgba(0, 0, 0, 0.15)'); // 设置背景变暗
  };

  const showResultDialogfalse = () => {
    setModalVisible(true);
    setSuccess(false);
    setBackgroundTransparent('0, 0, 0, 0.15'); // 恢复背景透明度
  };

  const init = async ()=>{

    const {unit} = route.params;
    setUnit(unit);
    console.log(unit);
    let m = await Getjsonwords(unit);
    setCharacterlist(m);
    console.log('characterlist:\n' + characterlist);
    let n = await getUniqueFileUris();
    setFileUris(n);
    let o  =  await GetjsonData(unit);
    setHuozhong(o);
    setDaan(daan - 1);
    };

useEffect(()=>{
  init();
},[]);
useEffect(() => {
  let level = unit;
  let u = Number(level.slice(-1)) + 1;
  setBgc('asset:/adventure_game/adventure' + u + '_game.jpg');
},[daan,characterlist,num]);
  useEffect(() => {
    console.log(daan + 'sdsd');
  if (daan === 0 ){
    console.log(daan);
    let i = num;
      //可选的回调函数，状态更新后执行
     if (characterlist.length > 0 && characterlist.length > num) {
      GetChaizi(characterlist[i]).then(pian => {
              setBushou(pian);
              setDaan(pian.length);
              setWord(characterlist[i].wordName);
                  getbuttons(pian).then(pressbuttons => { // 获取按钮
                      setPressbutton(pressbuttons);
                  });

            });
            console.log('useEffect' + i);
      } else {
        showResultDialog();
      }
  }
}, [daan,characterlist,num]);

const makechoice = async(value:string ,index: number)=>{
  const buttonToChange = pressbutton.find(button => button.title === value);
  let c = false;
  if (bushou.includes(value)) {
    if (buttonToChange.value == 0){
      correctSound.play();
      console.log('执行完了动画');
      // 当你需要将音频归零时
      correctSound.setCurrentTime(0); // 参数是毫秒，这里设置为 0 毫秒
      buttonToChange.value = 1;
      await animate(index);
      setOpcity(1);
      if (daan <= 1) {
        await toCenter(pressbutton,buttonRefs);
        
        
      }
      setDaan(daan - 1);
      
      console.log('答案正确');
      console.log(c + '222222');
      if (daan <= 1) {
          console.log('答案选择完毕！');
          c = true;
          console.log('中间？？');
          setNum(num + 1);

        }
    } else { console.log('已经选择！');
      ToastAndroid.show('已经点击过啦！选择下一个吧！', ToastAndroid.SHORT);
              }
  }
  else {
    setSucc(succ - 1 );
    console.log(num); // 现在这里打印的是更新后的值
    if (succ === 0){
      showResultDialogfalse();
    }
    falseSound.play();
    console.log('Value not found in the array.');
  }
  if (daan <= 0){
  }

  return c;
};
      return (
        <ImageBackground
        resizeMode="stretch"
        style={[styles.container, { backgroundColor: backgroundTransparent }]}
        source={{uri: `${bgc}`}}
      >
        <View style={styles.wordStyle}>
        <Text style={styles.wordis}>{word}</Text>
        </View>

        <View style={styles.buttonContainer}>
          {pressbutton.map((pressbuttons,index) => (
            <Animated.View key={index} style={[styles.button, {
              transform: [{ translateX: animationValue[index]},{ translateY: animationValue2[index]}], // 使用动画值
            }]}>
              <TouchableOpacity
                key={index}
                ref={buttonRefs.current[index]}
                style={[styles.buttoninsider,{opacity: opt}]}
                onPress={async() =>{ if(op === 1){makechoice(pressbuttons.title,index) } }}
              >
                <View style={styles.buttonContent}>
                  <Text style={[styles.text, {opacity: op}]}>{pressbuttons.title}</Text>
                </View>
              </TouchableOpacity>
            </Animated.View>
          ))}
           <SoundPlay text={fileUris[huozhong[num]] + '.mp3'} isPlaying={false}   />
        </View>

        <Animated.View style={[styles.button, {
    position: 'absolute', // 使用绝对定位
    top: screenCenterY / 2 - 70,
    left: screenCenterX / 2 - 100,
    right: 0,
    bottom: 0,
    zIndex: 100, // 设置较高的zIndex值
  }]}>
              <TouchableOpacity 
                style={[styles.buttoninsider,{opacity: 1 - opt}]}
              >
                <View style={styles.buttonContent}>
                  <Text style={[styles.text, {opacity: 1 - opt }]}>{word}</Text>
                </View>
              </TouchableOpacity>
            </Animated.View>
        <Modal
      animationType="fade"
      transparent={true}
      visible={modalVisible}
      onRequestClose={() => {
        setModalVisible(!modalVisible);
      }}
    >
      <View style={styles.modalContainer}>
        <ResultDialog
          visible={modalVisible}
          success={success}
          toshop={()=>{}}
          tostudy={()=>{navigation.navigate('home');}}
        />
      </View>
    </Modal>
      </ImageBackground>
      );
    };
    export default Practise;
